from tqsdk import TqApi, TqAuth, TqKq
from tqsdk.ta import MA
import asyncio

async def dual_ma_strategy(symbol="SHFE.rb2405", short_period=5, long_period=15):
    # 初始化API（模拟盘使用TqKq，实盘需替换为TqAccount）
    api = TqApi(account=TqKq(), auth=TqAuth("你的天勤账号", "密码"))
    
    try:
        # 获取K线数据（1分钟周期）
        klines = api.get_kline_serial(symbol, duration_seconds=60, data_length=100)
        quote = api.get_quote(symbol)
        
        # 协程任务：计算均线
        async def calculate_ma():
            while True:
                await api.wait_update()
                if api.is_changing(klines):
                    klines["ma_short"] = MA(klines.close, short_period)
                    klines["ma_long"] = MA(klines.close, long_period)
        
        # 协程任务：执行交易逻辑
        async def execute_trade():
            position = api.get_position(symbol)
            while True:
                await api.wait_update()
                if api.is_changing(klines) and len(klines) > long_period:
                    # 均线交叉信号检测
                    cross_up = (klines.ma_short.iloc[-2] < klines.ma_long.iloc[-2] 
                               and klines.ma_short.iloc[-1] > klines.ma_long.iloc[-1])
                    cross_down = (klines.ma_short.iloc[-2] > klines.ma_long.iloc[-2] 
                                 and klines.ma_short.iloc[-1] < klines.ma_long.iloc[-1])
                    
                    # 开多仓逻辑
                    if cross_up and position.pos == 0:
                        print(f"【信号】5日均线上穿15日均线，开多仓")
                        order = api.insert_order(symbol=symbol, direction="BUY", offset="OPEN", volume=1)
                        await api.wait_update()
                        if order.status == "ALIVE":
                            print(f"已挂单：价格{order.limit_price}，数量1手")
                    
                    # 平仓逻辑
                    elif cross_down and position.pos > 0:
                        print(f"【信号】5日均线下穿15日均线，平仓")
                        api.insert_order(symbol=symbol, direction="SELL", offset="CLOSE", volume=position.pos)
        
        # 启动协程任务
        tasks = [
            api.create_task(calculate_ma()),
            api.create_task(execute_trade())
        ]
        await asyncio.gather(*tasks)
        
    except Exception as e:
        print(f"策略异常：{e}")
    finally:
        await api.close()  # 确保关闭API连接

if __name__ == "__main__":
    asyncio.run(dual_ma_strategy())